﻿using MQTTnet.Server;
using MQTTnet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace SimpleMqttTemplate
{
	public class MqttService
	{
		IMqttServerOptions _Options;
		IMqttServer _Server;

		Task task;
		public MqttService()
		{
			
		}

		public async Task CreateAsync()
		{
			// 创建MQTT服务器选项
			_Options = new MqttServerOptionsBuilder()
				.WithDefaultEndpoint()
				.WithConnectionValidator(new CustomConnectionValidator())
				.Build();

			// 创建MQTT服务器
			_Server = new MqttFactory().CreateMqttServer();
			await _Server.StartAsync(_Options);

			_Server.UseClientConnectedHandler(MqttConnection);


			_Server.UseApplicationMessageReceivedHandler(MqttClient_ApplicationMessageReceivedAsync);

			task =Task.Run(async() =>
			{
				while (true)
				{
					await Task.Delay(5000);

					await Publish("test",JsonConvert.SerializeObject(new {age=10,name="111"}));
					await Publish("aaa",JsonConvert.SerializeObject(new {age=100,name="111"}));
				}
			});

		}
		public async Task MqttConnection(MqttServerClientConnectedEventArgs e)
		{
			Console.WriteLine("有人连接过了");

			//await SubscribeAsync(e.ClientId,"ttt");
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		public async Task Publish(string topic,string msg)
		{

			var message = new MqttApplicationMessageBuilder()
						.WithTopic(topic) // 设置主题
						.WithPayload(msg) // 设置消息负载
					   .WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce) // 设置QoS等级WithQualityOfServiceLevel
						.WithRetainFlag(false) // 不保留消息
						.Build();
			await _Server.PublishAsync(message);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		public async Task SubscribeAsync(string clientId,string topic)
		{
			await _Server.SubscribeAsync(clientId, new MqttTopicFilterBuilder().WithTopic(topic).Build());
		}
		public async Task StopAsync()
		{
			// 停止MQTT服务器
			await _Server.StopAsync();
			Console.WriteLine("MQTT服务器已停止");
		}

		/// <summary>
		/// 消息接收事件处理
		/// </summary>
		/// <param name="e"></param>
		/// <returns></returns>
		private async Task MqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs e)
		{
			var message = Encoding.UTF8.GetString(e.ApplicationMessage.Payload); // 获取消息负载并解码
			Console.WriteLine($"Message received from topic {e.ApplicationMessage.Topic}: {message}");
			Console.WriteLine(e.ClientId);

			if (e.ApplicationMessage.Topic == "")//根据不同的主题处理消息
			{
				//收到任务数据  

			}
		}
	}
}
